package com.bub.pay.framework.wrap.handle;

import com.bub.pay.framework.common.base.Cause;
import com.bub.pay.framework.common.base.Module;
import com.bub.pay.framework.common.entity.model.RespObject;
import com.bub.pay.framework.common.exception.GlobalException;
import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestControllerAdvice
public class GlobalExceptionHandler {
    private final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @Value("${spring.application.name}")
    private String module;

    @ExceptionHandler(Exception.class)
    public Object handle(HttpServletRequest request, Exception exception) {
        LOGGER.error("exception|", exception);
        if (LOGGER.isDebugEnabled()) {
            request.getParameterMap().forEach((k, v) -> LOGGER.debug("k->{},v->{}", k, v[0]));
        }
        GlobalException ge = null;
        if (exception instanceof UnauthorizedException) {
            ge = new GlobalException(Module.which(module), Cause.no_auth, exception);
        } else if (exception instanceof BindException) {
            String message = ((BindException) exception).getBindingResult().getFieldError().getDefaultMessage();
            return new RespObject((Module.which(module).getSn() * GlobalException.CARRY) + Cause.params_fail.getCode(), message);
        } else if (!(exception instanceof GlobalException)) {
            ge = new GlobalException(Module.which(module), Cause.unknown, exception);
        } else {
            ge = (GlobalException) exception;
            LOGGER.error(ge.getInfo());
        }
        return new RespObject(ge);
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Object handle(MethodArgumentNotValidException e) {
        LOGGER.error("系统异常 | 参数拦截器异常:|{}", e);
        String defaultMess = "系统异常";
        List<ObjectError> errList = e.getBindingResult().getAllErrors();
        if (!errList.isEmpty()) {
            defaultMess = errList.get(0).getDefaultMessage();
        }
        return new RespObject((Module.which(module).getSn() * GlobalException.CARRY) + Cause.params_fail.getCode(),
                defaultMess);
    }

}
